<template>
  <div class="scaling-container">
 
    <!-- 统计信息 -->
    <div class="stats-section">
      <div class="stats">
        <div class="stat-card">
          <div class="stat-value">{{ stats.currentContainers }}</div>
          <div class="stat-label">当前容器数</div>
        </div>
        <div class="stat-card">
          <div class="stat-value">{{ stats.maxContainers }}</div>
          <div class="stat-label">最大容器数</div>
        </div>
        <div class="stat-card">
          <div class="stat-value">{{ stats.minContainers }}</div>
          <div class="stat-label">最小容器数</div>
        </div>
        <div class="stat-card">
          <div class="stat-value">{{ stats.scaleEvents }}</div>
          <div class="stat-label">今日伸缩事件</div>
        </div>
      </div>
    </div>

    <!-- 控制按钮 -->
    <div class="control-section">
      <el-button 
        :type="autoScalingEnabled ? 'success' : 'danger'" 
        @click="toggleAutoScaling"
        size="medium"
      >
        {{ autoScalingEnabled ? '自动伸缩已启用' : '自动伸缩已禁用' }}
      </el-button>
    </div>

    <!-- 监控区域 -->
    <div class="monitor-section">
      <div class="chart-container">
        <div class="chart-title">资源使用率监控</div>
        <div class="usage-chart">
          <!-- ECharts实时折线图 -->
          <div ref="chartRef" style="width: 100%; height: 100%;"></div>
        </div>
        <div class="resource-usage">
          <div class="usage-item">
            <div class="usage-value">{{ cpuUsage.toFixed(1) }}%</div>
            <div class="usage-label">CPU使用率</div>
          </div>
          <div class="usage-item">
            <div class="usage-value">{{ memoryUsage.toFixed(1) }}%</div>
            <div class="usage-label">内存使用率</div>
          </div>
          <div class="usage-item">
            <div class="usage-value">{{ gpuUsage.toFixed(1) }}%</div>
            <div class="usage-label">GPU使用率</div>
          </div>
        </div>
      </div>
      
      <div class="containers-status">
        <div class="chart-title">容器状态</div>
        <div class="status-list">
          <div class="status-item" v-for="(container, index) in containers" :key="index">
            <span>{{ container.name }}</span>
            <el-tag :type="container.status === '运行中' ? 'success' : 'danger'" size="small">{{ container.status }}</el-tag>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 策略配置 -->
    <div class="policy-config">
      <div class="chart-title">伸缩策略配置</div>
      <el-form class="policy-form" :model="scalingPolicy" label-width="100px">
        <div class="policy-row">
          <div class="slider-item">
            <span class="slider-label">CPU阈值扩容: {{ scalingPolicy.cpuScaleOutThreshold }}%</span>
            <el-slider 
              v-model="scalingPolicy.cpuScaleOutThreshold" 
              :min="50" 
              :max="100"
              show-input
            ></el-slider>
          </div>
          <div class="slider-item">
            <span class="slider-label">CPU阈值缩容: {{ scalingPolicy.cpuScaleInThreshold }}%</span>
            <el-slider 
              v-model="scalingPolicy.cpuScaleInThreshold" 
              :min="0" 
              :max="50"
              show-input
            ></el-slider>
          </div>
        </div>
        
        <div class="policy-row">
          <div class="slider-item">
            <span class="slider-label">内存阈值扩容: {{ scalingPolicy.memoryScaleOutThreshold }}%</span>
            <el-slider 
              v-model="scalingPolicy.memoryScaleOutThreshold" 
              :min="50" 
              :max="100"
              show-input
            ></el-slider>
          </div>
          <div class="slider-item">
            <span class="slider-label">内存阈值缩容: {{ scalingPolicy.memoryScaleInThreshold }}%</span>
            <el-slider 
              v-model="scalingPolicy.memoryScaleInThreshold" 
              :min="0" 
              :max="50"
              show-input
            ></el-slider>
          </div>
        </div>
        
        <div class="policy-row">
          <div class="slider-item">
            <span class="slider-label">GPU阈值扩容: {{ scalingPolicy.gpuScaleOutThreshold }}%</span>
            <el-slider 
              v-model="scalingPolicy.gpuScaleOutThreshold" 
              :min="50" 
              :max="100"
              show-input
            ></el-slider>
          </div>
          <div class="slider-item">
            <span class="slider-label">GPU阈值缩容: {{ scalingPolicy.gpuScaleInThreshold }}%</span>
            <el-slider 
              v-model="scalingPolicy.gpuScaleInThreshold" 
              :min="0" 
              :max="50"
              show-input
            ></el-slider>
          </div>
        </div>
        
        <div class="policy-row">
          <el-form-item label="最大容器数">
            <el-input-number 
              v-model="scalingPolicy.maxContainers" 
              :min="scalingPolicy.minContainers + 1" 
              :max="20"
              controls-position="right"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="最小容器数">
            <el-input-number 
              v-model="scalingPolicy.minContainers" 
              :min="1" 
              :max="scalingPolicy.maxContainers - 1"
              controls-position="right"
            ></el-input-number>
          </el-form-item>
        </div>
        
        <el-form-item>
          <el-button type="primary" @click="saveScalingPolicy">保存策略</el-button>
          <el-button @click="resetScalingPolicy">重置默认</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 伸缩历史 -->
    <div class="history-section">
      <div class="chart-title">伸缩历史记录</div>
      <el-table :data="scaleHistory" stripe>
        <el-table-column prop="time" label="时间" width="150"></el-table-column>
        <el-table-column prop="event" label="事件" width="120">
          <template slot-scope="scope">
            <span :class="scope.row.eventType">{{ scope.row.event }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="reason" label="原因"></el-table-column>
        <el-table-column prop="oldCount" label="原容器数" width="90"></el-table-column>
        <el-table-column prop="newCount" label="新容器数" width="90"></el-table-column>
      </el-table>
    </div>

    <footer class="footer">
      <p>© 2023 动态伸缩管理系统 - 基于资源使用情况的智能伸缩</p>
    </footer>
  </div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  name: 'DynamicScalingSystem',
  data() {
    return {
      // 统计信息
      stats: {
        currentContainers: 5,
        maxContainers: 10,
        minContainers: 2,
        scaleEvents: 3
      },
      
      // 自动伸缩状态
      autoScalingEnabled: true,
      
      // 资源使用率
      cpuUsage: 65,
      memoryUsage: 42,
      gpuUsage: 78,
      
      // 容器状态
      containers: [
        { name: '模型推理服务-1', status: '运行中' },
        { name: '模型推理服务-2', status: '运行中' },
        { name: '数据处理服务', status: '运行中' },
        { name: '训练任务服务', status: '运行中' },
        { name: '批量预测服务', status: '已停止' }
      ],
      
      // 伸缩策略
      scalingPolicy: {
        cpuScaleOutThreshold: 80,
        cpuScaleInThreshold: 30,
        memoryScaleOutThreshold: 85,
        memoryScaleInThreshold: 40,
        gpuScaleOutThreshold: 75,
        gpuScaleInThreshold: 25,
        maxContainers: 10,
        minContainers: 2
      },
      
      // 伸缩历史
      scaleHistory: [
        { time: '2023-06-20 10:25:36', event: '扩容', eventType: 'scale-up', reason: 'CPU使用率超过阈值(82%)', oldCount: 4, newCount: 5 },
        { time: '2023-06-20 09:15:22', event: '缩容', eventType: 'scale-down', reason: '内存使用率低于阈值(35%)', oldCount: 5, newCount: 4 },
        { time: '2023-06-20 08:05:18', event: '扩容', eventType: 'scale-up', reason: 'GPU使用率超过阈值(78%)', oldCount: 3, newCount: 4 }
      ],
      
      // 图表数据
      chartData: {
        timeData: Array.from({ length: 20 }, (_, i) => `${60 - i * 3}s`),
        cpuData: Array(20).fill(65),
        memoryData: Array(20).fill(42),
        gpuData: Array(20).fill(78)
      },
      
      // 控制状态
      loading: false,
      autoRefresh: false,
      refreshInterval: 60,
      
      // 图表实例和定时器
      chartInstance: null,
      intervalId: null
    };
  },
  mounted() {
    // 初始化图表
    this.$nextTick(() => {
      this.initChart();
    });
    
    // 模拟实时数据更新
    this.intervalId = setInterval(() => {
      // 随机波动资源使用率
      this.cpuUsage = Math.max(10, Math.min(95, this.cpuUsage + (Math.random() * 10 - 5)));
      this.memoryUsage = Math.max(15, Math.min(90, this.memoryUsage + (Math.random() * 8 - 4)));
      this.gpuUsage = Math.max(20, Math.min(98, this.gpuUsage + (Math.random() * 12 - 6)));
      
      // 更新图表数据
      this.updateChartData();
    }, 3000);
  },
  beforeDestroy() {
    if (this.intervalId) {
      clearInterval(this.intervalId);
    }
    if (this.chartInstance) {
      this.chartInstance.dispose();
    }
  },
  methods: {
    // 刷新数据
    refreshData() {
      this.loading = true;
      setTimeout(() => {
        this.loading = false;
        this.$message.success('数据刷新成功');
      }, 1000);
    },
    
    // 切换自动伸缩
    toggleAutoScaling() {
      this.autoScalingEnabled = !this.autoScalingEnabled;
      this.$message.success(`自动伸缩已${this.autoScalingEnabled ? '启用' : '禁用'}`);
    },
    
    // 保存伸缩策略
    saveScalingPolicy() {
      this.$message.success('伸缩策略保存成功');
      // 模拟策略应用后的效果
      this.stats.maxContainers = this.scalingPolicy.maxContainers;
      this.stats.minContainers = this.scalingPolicy.minContainers;
    },
    
    // 重置伸缩策略
    resetScalingPolicy() {
      Object.assign(this.scalingPolicy, {
        cpuScaleOutThreshold: 80,
        cpuScaleInThreshold: 30,
        memoryScaleOutThreshold: 85,
        memoryScaleInThreshold: 40,
        gpuScaleOutThreshold: 75,
        gpuScaleInThreshold: 25,
        maxContainers: 10,
        minContainers: 2
      });
      this.$message.info('策略已重置为默认值');
    },
    
    // 初始化图表
    initChart() {
      if (!this.$refs.chartRef) return;
      
      this.chartInstance = echarts.init(this.$refs.chartRef);
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          },
          formatter: function(params) {
            let result = params[0].name + '<br/>';
            params.forEach(function(item) {
              result += item.marker + ' ' + item.seriesName + ': ' + item.value.toFixed(1) + '%<br/>';
            });
            return result;
          }
        },
        legend: {
          data: ['CPU使用率', '内存使用率', 'GPU使用率']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.chartData.timeData
        },
        yAxis: {
          type: 'value',
          min: 0,
          max: 100,
          axisLabel: {
            formatter: '{value}%'
          }
        },
        series: [
          {
            name: 'CPU使用率',
            type: 'line',
            smooth: true,
            lineStyle: {
              width: 3,
              color: '#5470c6'
            },
            showSymbol: false,
            areaStyle: {
              opacity: 0.1,
              color: '#5470c6'
            },
            emphasis: {
              focus: 'series'
            },
            data: this.chartData.cpuData
          },
          {
            name: '内存使用率',
            type: 'line',
            smooth: true,
            lineStyle: {
              width: 3,
              color: '#91cc75'
            },
            showSymbol: false,
            areaStyle: {
              opacity: 0.1,
              color: '#91cc75'
            },
            emphasis: {
              focus: 'series'
            },
            data: this.chartData.memoryData
          },
          {
            name: 'GPU使用率',
            type: 'line',
            smooth: true,
            lineStyle: {
              width: 3,
              color: '#fac858'
            },
            showSymbol: false,
            areaStyle: {
              opacity: 0.1,
              color: '#fac858'
            },
            emphasis: {
              focus: 'series'
            },
            data: this.chartData.gpuData
          }
        ]
      };
      
      this.chartInstance.setOption(option);
    },
    
    // 更新图表数据
    updateChartData() {
      // 更新时间数据 - 任务管理器风格，60秒倒计时
      this.chartData.timeData.shift();
      this.chartData.timeData.push('0s');
      
      // 更新前面的时间标签（从1s到59s）
      for (let i = 0; i < this.chartData.timeData.length - 1; i++) {
        const seconds = parseInt(this.chartData.timeData[i]) + 3;
        this.chartData.timeData[i] = `${seconds}s`;
      }
      
      // 更新CPU数据
      this.chartData.cpuData.shift();
      this.chartData.cpuData.push(this.cpuUsage);
      
      // 更新内存数据
      this.chartData.memoryData.shift();
      this.chartData.memoryData.push(this.memoryUsage);
      
      // 更新GPU数据
      this.chartData.gpuData.shift();
      this.chartData.gpuData.push(this.gpuUsage);
      
      if (this.chartInstance) {
        this.chartInstance.setOption({
          xAxis: {
            data: this.chartData.timeData
          },
          series: [
            {
              data: this.chartData.cpuData
            },
            {
              data: this.chartData.memoryData
            },
            {
              data: this.chartData.gpuData
            }
          ]
        });
      }
    }
  }
};
</script>

<style scoped>
.scaling-container {
  padding: 20px;
}

.scaling-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header-left {
  display: flex;
  align-items: center;
}

.header-left h1 {
  margin: 0;
  margin-right: 15px;
  font-size: 20px;
  color: #303133;
}

.header-left .el-tag {
  margin-right: 10px;
}

.header-controls {
  display: flex;
  align-items: center;
}

.stats-section {
  margin-bottom: 20px;
}

.stats {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
}

.stat-card {
  padding: 15px;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  text-align: center;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #409EFF;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.control-section {
  margin-bottom: 20px;
  text-align: left;
}

.monitor-section {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 20px;
  margin-bottom: 20px;
}

@media (max-width: 992px) {
  .monitor-section {
    grid-template-columns: 1fr;
  }
}

.chart-container {
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.chart-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 15px;
  color: #303133;
}

.usage-chart {
  height: 300px;
  margin-bottom: 20px;
}

.resource-usage {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 15px;
}

.usage-item {
  text-align: center;
  padding: 15px;
  background: linear-gradient(45deg, #fdf6ec, #fef8f0);
  border-radius: 6px;
}

.usage-value {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 5px;
}

.usage-label {
  font-size: 14px;
  color: #909399;
}

.containers-status {
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.status-list {
  margin-top: 15px;
}

.status-item {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
  border-bottom: 1px solid #ebeef5;
}

.status-item:last-child {
  border-bottom: none;
}

.policy-config {
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
}

.policy-form {
  margin-top: 20px;
}

.policy-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 20px;
}

@media (max-width: 768px) {
  .policy-row {
    grid-template-columns: 1fr;
  }
}

.slider-item {
  margin-bottom: 25px;
}

.slider-label {
  display: block;
  margin-bottom: 8px;
  color: #606266;
}

.history-section {
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.footer {
  text-align: center;
  padding: 20px;
  color: #909399;
  font-size: 14px;
  margin-top: 20px;
}

.scale-up {
  color: #67c23a;
}

.scale-down {
  color: #f56c6c;
}

@media (max-width: 768px) {
  .stats {
    grid-template-columns: 1fr 1fr;
  }
  
  .resource-usage {
    grid-template-columns: 1fr;
  }
  
  .scaling-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .header-controls {
    margin-top: 15px;
    width: 100%;
    justify-content: flex-start;
  }
}
</style>
